package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.service.PortRPCService;
import id.net.iconpln.bb.client.service.PortRPCServiceAsync;
import id.net.iconpln.bb.client.service.StockRPCService;
import id.net.iconpln.bb.client.service.StockRPCServiceAsync;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageBbStockOpname extends LayoutContainer {
	private final StockRPCServiceAsync service = GWT.create(StockRPCService.class);
	private FormBinding formBindings;  
	private FormData formData; 
	private ListStore storeStock,storeKplAntri, storeJetty;
	private Grid gridStock, gridKplAntri;
	private ComboBox cboJetty;
	private DateField tanggal, tglTd;
	private TextField<String> noOpname;
	private Button bSubmit;
	
	  @Override  
	  protected void onRender(Element parent, int index) {  
	    super.onRender(parent, index);  
	    setLayout(new FitLayout());
	    initStore();
	    
	    formData = new FormData("-20"); 
	    ContentPanel cp = new ContentPanel();  
	   
	    cp.setHeaderVisible(false);
	    cp.setFrame(true);  
	    cp.setSize(900, 400);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL)); 
  
	  
	    gridStock = createGridStock();  

	    ToolBar tbStock = new ToolBar();
	    tbStock.add(new LabelToolItem("<b>Data Stock Opname</b>"));
	    tbStock.add(new SeparatorToolItem());
	    
	    stockOpname("listStock","OPNAME");
	    

	    FormPanel panel = createForm(); 
	    panel.setScrollMode(Scroll.AUTO);
	    formBindings = new FormBinding(panel, true);    
	    
	    
	    ContentPanel pStock = new ContentPanel();
	    pStock.setHeaderVisible(false);
	    pStock.setLayout(new RowLayout(Orientation.HORIZONTAL));
	    pStock.add(gridStock,new RowData(1, 1));
	    pStock.setTopComponent(tbStock);

	    
	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);
	    p.setLayout(new RowLayout(Orientation.VERTICAL));	    	    
	    p.add(pStock, new RowData(.99, 1));
//	    p.add(pKplAntri, new RowData(.99, .5));
//	    p.setTopComponent(tbPltu);

	    
	    cp.add(panel, new RowData(.4, 1));
	    cp.add(p, new RowData(.6, 1));
	    
	   	
	    add(cp, new FitData(5));  
	  }  
	  
	  private void initStore(){
		  storeStock = new ListStore(); 
//		  storeKplAntri = new ListStore(); 
//		  storeJetty = new ListStore();
	  }

	  
	  private FormPanel createForm() {  
	    FormPanel panel = new FormPanel();	    
	    panel.setHeaderVisible(false);
	    
	    FieldSet fieldSet = new FieldSet();  
	    fieldSet.setHeading("Informasi Stock Opname");  
	    fieldSet.setCollapsible(false);
	    
	  
	    FormLayout layout = new FormLayout();  
	    layout.setLabelWidth(180);  
	    fieldSet.setLayout(layout);  

	    noOpname = new TextField<String>();  
	    noOpname.setName("no_opname");  
	    noOpname.setFieldLabel("No Stock Opname");    
//	    noOpname.setVisible(false);
	    noOpname.setReadOnly(true);
	    fieldSet.add(noOpname, formData);	
	    
	    
	    final TextField<String> noSertifikatOpname = new TextField<String>();  
	    noSertifikatOpname.setName("no_surat");
	    noSertifikatOpname.setValidateOnBlur(true);
	    noSertifikatOpname.setFieldLabel("No Srtifkt Opname");    
	    fieldSet.add(noSertifikatOpname, formData);	  	  

	    final TextField<String> indSurveyor = new TextField<String>();  
	    indSurveyor.setName("independen_surveyor");
	    indSurveyor.setValidateOnBlur(true);
	    indSurveyor.setFieldLabel("Ind. Surveyor");    
	    fieldSet.add(indSurveyor, formData);	  	  
	    
	    final TextField<String> volAwal = new TextField<String>();  
	    volAwal.setName("volume_awal");
	    volAwal.setFieldLabel("Stock Awal");    
	    fieldSet.add(volAwal, formData);	  	  
	    	     

	    final TextField<String> volOpname = new TextField<String>();	    
	    volOpname.setName("volume_opname"); 
	    volOpname.setValidateOnBlur(true);
	    volOpname.setFieldLabel("Stock Opname");    
	    fieldSet.add(volOpname, formData);


	    
//	    TextField<String> tanggal = new TextField<String>();
	    tanggal = new DateField();
	    tanggal.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
//	    tanggal.setName("time");  
	    tanggal.setFieldLabel("Tanggal");    
	    fieldSet.add(tanggal, formData);


	    panel.add(fieldSet);

	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);	    
	    p.setButtonAlign(HorizontalAlignment.RIGHT);  
	    p.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {  
	      @Override  
	      public void componentSelected(ButtonEvent ce) {  
//	        grid.getStore().rejectChanges();  
	      }  
	    }));  
	    bSubmit = new Button("Submit");
	    p.addButton(bSubmit);
	    
	    bSubmit.addSelectionListener(new SelectionListener<ButtonEvent>() {
	      @Override  
	      public void componentSelected(ButtonEvent ce) {  

	    	  MessageBox.confirm("Info", "Apakah Anda Yakin Ingin Menyimpan Data?",new Listener<MessageBoxEvent>() {

				@Override
				public void handleEvent(MessageBoxEvent be) {
					// TODO Auto-generated method stub
					Button btn = be.getButtonClicked();
					if (btn.getText().equals("Yes")){
					
			    	  	Map mapParam = new FastMap();
			    	  	mapParam.put("volume_opname", volOpname.getRawValue());
			    	  	mapParam.put("volume_awal", volAwal.getValue());
			    	  	mapParam.put("independen_surveyor",indSurveyor.getRawValue());
			    		mapParam.put("tanggal", tanggal.getRawValue());	    		
			    		mapParam.put("no_surat", noSertifikatOpname.getValue());
			    	    mapParam.put("id_pltu", Registry.get("idPltu").toString());
			    		mapParam.put("createby", Registry.get("whoAmI").toString());
			    		mapParam.put("app_access", "WEB");
			    		mapParam.put("crud", "CREATE");
			    		
			    		Set set = mapParam.entrySet(); 
			    		Iterator i = set.iterator();  
			    		while(i.hasNext()) { 
			    		Map.Entry me = (Map.Entry)i.next(); 
				    		GWT.log(me.getKey() + ": " + me.getValue()); 
			    		} 
			    		
			    		service.insertStock("OPNAME", mapParam,new AsyncCallback<List<Map>>() {
			    			public void onFailure(Throwable caught) {
			    				GWT.log(caught.getMessage(), null);
			    			}
	
			    			public void onSuccess(List<Map> result) {	    				
	    				
			    				gridStock.mask("load Data ....","x-mask-loading");
			    				stockOpname("listStock","OPNAME");
			    				
			    				MessageBox.alert("Informasi", " " + result, null);
			    			}
			    		});
					}		
		    		//--
				}
			});
	      }  
	    });  

	    panel.add(p);
	    
	    return panel;  
	  }  


	  
	  private Grid createGridStock() {  
	  
		    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

		    ColumnConfig column = new ColumnConfig();	    	     
		    
		    column = new ColumnConfig();  
		    column.setId("tanggal");  
		    column.setHeader("Tanggal");  
		    column.setDateTimeFormat(DateTimeFormat.getFormat("dd/MM/yyyy"));
		    column.setWidth(150);  
		    configs.add(column);  
		    
		    column = new ColumnConfig();  
		    column.setId("volume_awal");  
		    column.setHeader("Stock Awal");    
		    column.setWidth(150);    
		    configs.add(column);  

		    column = new ColumnConfig();  
		    column.setId("volume_opname");  
		    column.setHeader("Stock Opname");  
		    column.setWidth(100);  
		    configs.add(column);  	
		    
		    
		    		    
		    column = new ColumnConfig();  
		    column.setId("no_surat");  
		    column.setHeader("NO Sertifikat");    
		    column.setWidth(100);    
		    configs.add(column);

		    column = new ColumnConfig();  
		    column.setId("independen_surveyor");  
		    column.setHeader("Ind. Surveyor");    
		    column.setWidth(100);    
		    configs.add(column);
		    	            		     
		    storeStock.setMonitorChanges(true);  
		  
		    ColumnModel cm = new ColumnModel(configs);  
	  
	    gridStock = new Grid(storeStock, cm);  
	    gridStock.getView().setEmptyText("Data Empty");
	    gridStock.setLoadMask(true);  
	    gridStock.mask("load Data ...","x-mask-loading");
	    gridStock.setBorders(false);  
	    gridStock.setBorders(true);  
//	    gridStock.addListener(Events.CellClick, new Listener<BaseEvent>() {            
//            public void handleEvent(BaseEvent ge) {
//            	try{
//            		String tgl_ta = gridStock.getSelectionModel().getSelectedItem().get("tgl_ta");
//            		String tgl_td = gridStock.getSelectionModel().getSelectedItem().get("tgl_td");
////            		String norakor = gridKplAntri.getSelectionModel().getSelectedItem().get("kode_jetty").toString();
////                	SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy"); 
////                	Date tgl = dateFormat.parse(test);
//                	tglTd.setRawValue(tgl_td);
//                	tanggal.setRawValue(tgl_ta);
////                	cboJetty.setRawValue(norakor);
////                	noOpname.setVisible(false);
//                	
////                	getdataRakor_kon(norakor);
//                	
//            	}catch (Exception e) {
//					// TODO: handle exception
//            		e.getMessage();
//				}
//
//             	
//            }
//		});

	    return gridStock;  
	  }  
	  
	  private void stockOpname(String kode, final String codectrl){
		  Map mapParam = new FastMap();

		  mapParam.put("id_pltu", Registry.get("idPltu").toString());
		  
		  if (kode.equals("listStock")){
  		  service.getListStock(codectrl, mapParam,new AsyncCallback<List<Map>>() {
  			public void onFailure(Throwable caught) {
  				GWT.log(caught.getMessage(), null);  			  				
  			}

  			public void onSuccess(List<Map> result) {
  	  				storeStock.removeAll();
  	  			    storeStock.add(ClientModule.setListBaseModelFromListMap(result));
  	  				gridStock.unmask();
  					  				
  			}
  		});

	    }
	  }

}
